package com.jingzhi.huimiao;

import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jingzhi.huimiao.bean.WordInfo;
import com.jingzhi.huimiao.utils.CXRadom;
import com.jingzhi.huimiao.utils.DataStoreUtil;
import com.jingzhi.huimiao.utils.SQLdm;

/**
 * 背单词页面
 * 
 * @author cxk
 * 
 * 
 */
public class TestActivity extends Activity implements OnClickListener {

	private static final int WHAT = 0;
	private static final int LASTWHAT = 1;
	private TextView textview1;// 单词
	private TextView textview2;
	private TextView textview3;
	private TextView textview4;
	private TextView textview5;
	private TextView textview6;// 音标
	private TextView textview7;// 词意
	private TextView textview8;// 例句翻译
	private LinearLayout iv_back_task;
	private RelativeLayout rl_test;
	private RelativeLayout rl_content;
	private ImageView icon_save;
	private ImageView iv_lastone;
	private TextView tv_title;
	private ProgressBar pb_test;
	private ImageView iv_sound;
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:

				if (i < wordlist.size() - 1) {
					i++;

					// 根据随机数来判断是根据 英语-->汉语 还是 汉语-->英语
					int a;
					a = new Random().nextInt(23);
					if (i < a) {
						// 英语-->汉语
						studyWord(wordlist);
					} else {
						// 汉语-->英语
						studyWord2(wordlist);
					}
					
					pb_test.incrementProgressBy(1);
				} else {

					// Toast.makeText(TestActivity.this, "已经最后一个了....",
					// 0).show();
					startActivity(new Intent(TestActivity.this,
							TaskActivity.class));
					finish();
				}

				break;
			case 1:

				if (i > 0) {
					i--;

					// 根据随机数来判断是根据 英语-->汉语 还是 汉语-->英语
					int a;
					a = new Random().nextInt(23);
					if (i < a) {
						// 英语-->汉语
						studyWord(wordlist);
					} else {
						// 汉语-->英语
						studyWord2(wordlist);
					}
					
					pb_test.incrementProgressBy(-1);
				} else {

					 Toast.makeText(TestActivity.this, "已经第一个了....",
					 0).show();
//					startActivity(new Intent(TestActivity.this,
//							EndTestActivity.class));
//					finish();
				}

				break;
			default:
				break;
			}
		}

	};
	private Cursor cursor;
	private long wordid;
	private int i;
	private ArrayList<WordInfo> wordlist;
	private SQLiteDatabase db;
	private String sday;
	private String smonth;
	private Cursor isinwrong;
	private int wrongtype;
//	private MediaPlayer music;
	private String headS;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_test);

		initView();

		long taskid = DataStoreUtil.getLong(TestActivity.this, "CHOOSETASK");
		//设置TestActivity的标题
		tv_title.setText("Task"+""+((taskid-57)%3+1));
		
		
		
		pb_test.setProgress(1);
		
		// 打开数据库输出流
		SQLdm s = new SQLdm();
		db = s.openDatabase(getApplicationContext());

		// 查询数据库中testid=1的数据

		wordlist = new ArrayList<WordInfo>();

		cursor = db.rawQuery("select * from word where pid=?",
				new String[] { taskid + "" });
		Log.e("Taskid--------test", taskid + "");
		String name = null;
		String translation = null;
		String example = null;

		while (cursor.moveToNext()) {
			WordInfo wordinfo = new WordInfo();
			wordinfo.id = cursor.getLong(cursor.getColumnIndex("id"));
			wordinfo.wname = cursor.getString(cursor
					.getColumnIndex("word_name"));
			wordinfo.wexamp = cursor.getString(cursor
					.getColumnIndex("word_example"));
			wordinfo.wtrans = cursor.getString(cursor
					.getColumnIndex("word_translation"));
			wordinfo.wex_tr = cursor.getString(cursor
					.getColumnIndex("word_example_translation"));
			wordinfo.wsoundm = cursor.getString(cursor
					.getColumnIndex("word_soundmark"));
			wordinfo.pid = cursor.getLong(cursor.getColumnIndex("pid"));
			wordlist.add(wordinfo);

			// Toast.makeText(TestActivity.this,wordinfo.wname, 0).show();
		}

		studyWord(wordlist);

		// i=wordlist.size()-1;
		pb_test.setMax(wordlist.size());
	}

	private void studyWord(ArrayList<WordInfo> wordlist) {
		restoreColor();
		textview1.setText(wordlist.get(i).wname);
		textview6.setText(wordlist.get(i).wsoundm);
		textview6.setVisibility(View.VISIBLE);
		List<String> answerList = CXRadom.getWrongAn(wordlist.get(i).wtrans);
		String answer = null;

		int position = new Random().nextInt(4);
		int ps = Math.abs(position);
		// answer = answerList.get(position);
		switch (ps) {
		case 0:
			textview2.setText(answerList.get(3));
			textview3.setText(answerList.get(0));
			textview4.setText(answerList.get(1));
			textview5.setText(answerList.get(2));
			break;
		case 1:
			textview3.setText(answerList.get(3));
			textview2.setText(answerList.get(0));
			textview4.setText(answerList.get(1));
			textview5.setText(answerList.get(2));
			break;
		case 2:
			textview4.setText(answerList.get(3));
			textview2.setText(answerList.get(0));
			textview3.setText(answerList.get(1));
			textview5.setText(answerList.get(2));
			break;
		default:
			textview5.setText(answerList.get(3));
			textview2.setText(answerList.get(0));
			textview3.setText(answerList.get(1));
			textview4.setText(answerList.get(2));
			break;
		}

		addListener();
	}

	/**
	 * 汉----->英 根据汉语选择英语答案的学习方法
	 */
	private void studyWord2(ArrayList<WordInfo> wordlist) {
		// TODO Auto-generated method stub
		restoreColor();
		textview1.setText(wordlist.get(i).wtrans);
		textview1.setTextSize(20);
		textview6.setVisibility(View.INVISIBLE);
		List<String> answerList = CXRadom.getWrongAn2(wordlist.get(i).wname);
		String answer = null;

		int position = new Random().nextInt(4);
		int ps = Math.abs(position);
		// answer = answerList.get(position);
		switch (ps) {
		case 0:
			textview2.setText(answerList.get(3));
			textview3.setText(answerList.get(0));
			textview4.setText(answerList.get(1));
			textview5.setText(answerList.get(2));
			break;
		case 1:
			textview3.setText(answerList.get(3));
			textview2.setText(answerList.get(0));
			textview4.setText(answerList.get(1));
			textview5.setText(answerList.get(2));
			break;
		case 2:
			textview4.setText(answerList.get(3));
			textview2.setText(answerList.get(0));
			textview3.setText(answerList.get(1));
			textview5.setText(answerList.get(2));
			break;
		default:
			textview5.setText(answerList.get(3));
			textview2.setText(answerList.get(0));
			textview3.setText(answerList.get(1));
			textview4.setText(answerList.get(2));
			break;
		}

		addListener();
	}

	private void initView() {
		textview1 = (TextView) findViewById(R.id.textView1);
		textview2 = (TextView) findViewById(R.id.textView2);
		textview3 = (TextView) findViewById(R.id.textView3);
		textview4 = (TextView) findViewById(R.id.textView4);
		textview5 = (TextView) findViewById(R.id.textView5);
		textview6 = (TextView) findViewById(R.id.textView6);
		textview7 = (TextView) findViewById(R.id.tv_translation);
		textview8 = (TextView) findViewById(R.id.tv_example);
		icon_save = (ImageView) findViewById(R.id.iv_save);
		iv_lastone = (ImageView) findViewById(R.id.iv_lastone);
		iv_back_task = (LinearLayout) findViewById(R.id.iv_back_tomain);
		rl_test = (RelativeLayout) findViewById(R.id.rl_test);
		rl_content = (RelativeLayout) findViewById(R.id.rl_content);
		tv_title = (TextView) findViewById(R.id.tv_title);
		pb_test = (ProgressBar) findViewById(R.id.pb_test);
		
		iv_sound = (ImageView) findViewById(R.id.iv_sound);
	}

	private void addListener() {
		textview2.setOnClickListener(this);
		textview3.setOnClickListener(this);
		textview4.setOnClickListener(this);
		textview5.setOnClickListener(this);
		iv_back_task.setOnClickListener(this);
		icon_save.setOnClickListener(this);
		iv_lastone.setOnClickListener(this);
		rl_test.setOnClickListener(this);
		
		iv_sound.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		restoreColor();
		switch (v.getId()) {

		case R.id.textView2:
			judgeAnswer(textview2);

			break;
		case R.id.textView3:
			judgeAnswer(textview3);
			break;
		case R.id.textView4:
			judgeAnswer(textview4);

			break;
		case R.id.textView5:
			judgeAnswer(textview5);
			break;
		case R.id.iv_back_tomain:
			startActivity(new Intent(TestActivity.this, TaskActivity.class));
			finish();
			break;
		case R.id.iv_save:
			//收藏单词
			saveWord();
			icon_save.setBackgroundResource(R.drawable.icon_save1);
			break;
		case R.id.iv_lastone:
			handler.sendEmptyMessage(LASTWHAT);
			break;
		case R.id.iv_sound:
			
//			//获取单词首字母  (美音)
//			String substring = wordlist.get(i).wname.substring(0,1);
//			char[] tem = wordlist.get(i).wname.substring(0,1).toCharArray();
//			int head = tem[0];
//			if(head>=97&&head<=122){//小写字母
//				headS = wordlist.get(i).wname.substring(0,1).toUpperCase();
//			
//			}else{
//				headS = wordlist.get(i).wname.substring(0,1);
//			}
			
			String path = "http://limshare.com/app/uk/"+wordlist.get(i).wname.trim()+".mp3";
			Log.e("TAG----", path);
			//"http://limshare.com/app/wordsound/A/abrupt.mp3"  (美音)
			//"http://limshare.com/app/uk/abandon.mp3" (英音)
			try {
				MediaPlayer music = new MediaPlayer();
				music.setDataSource(path);
				music.prepare();
				music.start();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Toast.makeText(TestActivity.this, "还没有这个单词的语音哦", 0).show();
			}
			break;
		case R.id.rl_test:
			rl_test.setVisibility(8);
			handler.sendEmptyMessageDelayed(WHAT, 200);
			break;

		default:
			break;
		}
	}

	private void saveWord() {
		// TODO Auto-generated method stub
		ContentValues values = new ContentValues();
		values.put("word_right", 1);// key为字段名，value为值
		db.update("word", values, "id=?",
				new String[] { wordlist.get(i).id + "" });

		long wordid = wordlist.get(i).id;
		long user_id = DataStoreUtil.getLong(TestActivity.this, "userid");
		Date date = new Date(System.currentTimeMillis());
//		String str = formatter.format(date); 
		Log.e("time", date+"-----");
		// String date=formatter.format(new java.util.Date());
		int wrongtype=0;
		//判断生词本中是否有该单词
		Cursor isinwrong = db.rawQuery("select * from word where id='"+wordid+"';", null);
		if(isinwrong.moveToFirst()) {
			wrongtype = isinwrong.getInt(isinwrong.getColumnIndex("wrong_type"));
			Log.e("TAG---wrongtype", wrongtype+"");
		}
		if(wrongtype == 0){
			db.execSQL("insert into wrong_word (user_id,word_id,insert_time) values ("
					+ user_id + "," + wordid + ",'" + date + "');");
			//更新wrongtype为1
			db.execSQL("update word set wrong_type=1 where id='"+wordid+"';");
		}else{
			//根据单词ID更新wrong_word的插入时间
			db.execSQL("update wrong_word set insert_time='"+date+"' where word_id="+wordid+";");
		}
		if(isinwrong!=null){
			isinwrong.close();
		}
	}

	private void restoreColor() {
		icon_save.setBackgroundResource(R.drawable.icon_save);
		textview2.setBackgroundResource(R.drawable.text_color);
		textview3.setBackgroundResource(R.drawable.text_color);
		textview4.setBackgroundResource(R.drawable.text_color);
		textview5.setBackgroundResource(R.drawable.text_color);
	}

	/**
	 * 对选择的汉语答案进行判断
	 */
	private void judgeAnswer(TextView textview) {

		long user_id = DataStoreUtil.getLong(TestActivity.this, "userid");
		long role_id = DataStoreUtil.getLong(TestActivity.this, "roleid");
		long wordid = wordlist.get(i).id;

		// Log.i("role_id", role_id+"");
		// Log.i("role_id----", wordid+"");
		// Log.i("role_id----ddd", user_id+"");
		/**
		 * 对当前看到的单词数进行记录
		 */
		// 记录单词进度
		if (role_id == 1) {
			ContentValues v = new ContentValues();
			v.put("word_id", wordlist.get(i).id);
			db.update("role1", v, "user_id=" + user_id + "", null);

			// if(word_progress.)
		} else if (role_id == 2) {
			Log.e("jinbujin", "jinbujin");
			ContentValues v = new ContentValues();
			v.put("word_id", wordlist.get(i).id);

			db.update("role2", v, "user_id=" + user_id + "", null);

		} else {
			ContentValues v = new ContentValues();
			v.put("word_id", wordlist.get(i).id);
			db.update("role3", v, "user_id=" + user_id + "", null);
		}

		textview.setBackgroundResource(R.drawable.text_color);
		String uersan = textview.getText().toString();

		// 判断答案是英文还是中文

		if (uersan.contains(".")) {// 如果答案是中文，说明是英译中
			if (uersan.equals(wordlist.get(i).wtrans)) {

				// db.execSQL("update word set word_right=2 where id="+wordlist.get(i).id+";");

				ContentValues values = new ContentValues();
				values.put("word_right", 2);// key为字段名，value为值
				db.update("word", values, "id=?",
						new String[] { wordlist.get(i).id + "" });

				textview.setBackgroundColor(Color.GREEN);
				// Message msg = new Message();
				Toast.makeText(TestActivity.this, "回答正确....", 0).show();
				handler.sendEmptyMessageDelayed(WHAT, 500);

				/*
				 * SQLiteDatabase db = databaseHelper.getWritableDatabase();
				 * ContentValues values = new ContentValues();
				 * values.put(“name”, “林计钦”);//key为字段名，value为值
				 * db.update("person", values, "personid=?", new String[]{"1"});
				 * db.close();
				 */

			} else {
				
				
				
				textview.setBackgroundColor(Color.RED);
				// Log.e("错误。。。。。", wordlist.get(i).id+"");
				ContentValues values = new ContentValues();
				values.put("word_right", 1);// key为字段名，value为值
				db.update("word", values, "id=?",
						new String[] { wordlist.get(i).id + "" });

				Date date = new Date(System.currentTimeMillis());
//				String str = formatter.format(date); 
				Log.e("time", date+"-----");
				// String date=formatter.format(new java.util.Date());
				
				//判断生词本中是否有该单词
				isinwrong = db.rawQuery("select * from word where id='"+wordid+"';", null);
				if(isinwrong.moveToFirst()) {
					wrongtype = isinwrong.getInt(isinwrong.getColumnIndex("wrong_type"));
					Log.e("TAG---wrongtype", wrongtype+"");
				}
				if(wrongtype == 0){
					Log.e("TAG----", wrongtype+"00");
					db.execSQL("insert into wrong_word (user_id,word_id,insert_time) values ("
							+ user_id + "," + wordid + ",'" + date + "');");
					//更新wrongtype为1
					db.execSQL("update word set wrong_type=1 where id='"+wordid+"';");
				}else{
					Log.e("TAG----", wrongtype+"1111");
					//根据单词ID更新wrong_word的插入时间
					db.execSQL("update wrong_word set insert_time='"+date+"' where word_id="+wordid+";");
				}
				

				textview7.setText(wordlist.get(i).wtrans);
				textview8.setText(wordlist.get(i).wexamp
						+ wordlist.get(i).wex_tr);
				setNoClick();
				rl_test.setVisibility(0);
				// Toast.makeText(TestActivity.this, "回答错误！！！！", 0).show();

			}
		} else {// 答案为英文，说明是中译英
			if (uersan.equals(wordlist.get(i).wname)) {

				// db.execSQL("update word set word_right=2 where id="+wordlist.get(i).id+";");

				ContentValues values = new ContentValues();
				values.put("word_right", 2);// key为字段名，value为值
				db.update("word", values, "id=?",
						new String[] { wordlist.get(i).id + "" });

				textview.setBackgroundColor(Color.GREEN);
				// Message msg = new Message();
				Toast.makeText(TestActivity.this, "回答正确....", 0).show();
				handler.sendEmptyMessageDelayed(WHAT, 500);
			} else {
				textview.setBackgroundColor(Color.RED);
				// Log.e("错误。。。。。", wordlist.get(i).id+"");
				ContentValues values = new ContentValues();
				values.put("word_right", 1);// key为字段名，value为值
				db.update("word", values, "id=?",
						new String[] { wordlist.get(i).id + "" });

				//保存到生词本
				Date date = new Date(System.currentTimeMillis());
				// String date=formatter.format(new java.util.Date());
				
				//判断生词本中是否有该单词
				isinwrong = db.rawQuery("select * from word where id='"+wordid+"';", null);
				if(isinwrong.moveToFirst()) {
					wrongtype = isinwrong.getInt(isinwrong.getColumnIndex("wrong_type"));
					Log.e("TAG---wrongtype", wrongtype+"");
					
				}
				if(wrongtype == 0){
					Log.e("TAG----", wrongtype+"00");
					db.execSQL("insert into wrong_word (user_id,word_id,insert_time) values ("
							+ user_id + "," + wordid + ",'" + date + "');");
					//更新wrongtype为1
					db.execSQL("update word set wrong_type=1 where id='"+wordid+"';");
				}else{
					Log.e("TAG----", wrongtype+"1111");
					//根据单词ID更新wrong_word的插入时间
					db.execSQL("update wrong_word set insert_time='"+date+"' where word_id="+wordid+";");
				}
				
				
				
				textview7.setText(wordlist.get(i).wtrans);
				textview8.setText(wordlist.get(i).wexamp
						+ wordlist.get(i).wex_tr);
				setNoClick();
				rl_test.setVisibility(0);
			}
		}
		
		if (isinwrong != null) {
			isinwrong.close();
		}
	}

	/**
	 * 设置按钮不可点击
	 */
	private void setNoClick() {
		textview2.setClickable(false);
		textview3.setClickable(false);
		textview4.setClickable(false);
		textview5.setClickable(false);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		
		if (cursor != null) {
			cursor.close();
		}
		if (db != null) {
			db.close();
		}

	}
}
